package com.flute.haflute.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import com.flute.haflute.jobbox.common.CloudConstants;
import com.flute.haflute.jobbox.processes.Param;
import com.flute.haflute.jobbox.processes.Process;
import com.flute.haflute.jobbox.processes.Processes;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 用于分析XML文件类
 * 
 * @author Jazz
 * @date 2010-7-7
 */
public class ParseXMLUtil {
	private static final String VALUE_ALIAS = "value";
	private static final String CLAZZ_ALIAS = "clazz";
	private static final String CLZ_ATTI = "clz";
	private static final String NAME_ALIAS = "name";
	private static final String PARAM_ALIAS = "param";
	private static final String PROCESS_ALIAS = "process";
	private static final String PROCESSES_ALIAS = "processes";

	public static Processes getProcessesFromXML(String xml) {
		Object obj = getProcessesXStream().fromXML(xml);
		return getProcessesIfValid(obj);
	}

	private static Processes getProcessesIfValid(Object obj) {
		if (obj instanceof Processes) {
			return (Processes) obj;
		} else {
			throw new RuntimeException(
					"The processes xml is invalid. Can't convert it to Processes.");
		}
	}

	public static Processes getProcessesFromXML(InputStream xml) {
		Object obj = getProcessesXStream().fromXML(xml);
		return getProcessesIfValid(obj);
	}

	private static XStream getProcessesXStream() {
		XStream xStream = new XStream(new DomDriver());
		xStream.setMode(XStream.NO_REFERENCES);
		xStream.alias(PROCESSES_ALIAS, Processes.class);
		xStream.alias(PROCESS_ALIAS, Process.class);
		xStream.alias(PARAM_ALIAS, Param.class);
		xStream.aliasAttribute(Process.class, NAME_ALIAS, NAME_ALIAS);
		xStream.aliasAttribute(Process.class, CLZ_ATTI, CLAZZ_ALIAS);
		xStream.aliasAttribute(Param.class, NAME_ALIAS, NAME_ALIAS);
		xStream.aliasAttribute(Param.class, VALUE_ALIAS, VALUE_ALIAS);
		xStream.addImplicitCollection(Processes.class, PROCESSES_ALIAS);

		return xStream;
	}

	/**
	 * @param args
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException {
		File file = new File(CloudConstants.CUSTOM_PROCESSES_FILENAME);
		InputStream is = new FileInputStream(file);
		getProcessesXStream().fromXML(is);
	}
}
